package modalities;

import java.util.Observable;


import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.InputChangeEvent;
import com.phidgets.event.InputChangeListener;
import com.phidgets.event.SensorChangeEvent;
import com.phidgets.event.SensorChangeListener;


public class Phidgets extends Observable {

	String name;
	double minVal;
	double maxVal;
	static double angleRead=0;
	static double positionReadMin;
	static double positionReadMax;
	static double pressure;
	static String inputDevice="";

	//ModifSimulation th;
	Decider boss;

	static InterfaceKitPhidget interfaceKitPhidget;

	public Phidgets(double minVal, double maxVal, String name, Decider boss)
	{
		this.minVal = minVal;
		this.maxVal = maxVal;
		this.name = name;
		this.boss = boss;
		//The decider watch at the phidget
		addObserver(boss);

		try {
			interfaceKitPhidget = new InterfaceKitPhidget();
			interfaceKitPhidget.openAny();
			interfaceKitPhidget.waitForAttachment();
			interfaceKitPhidget.addSensorChangeListener(new SensorChangeListener() {
				@Override
				public void sensorChanged(SensorChangeEvent se) {

					switch (se.getIndex()){
					case 0:// Cursor dans le second port
						//curseur= se.getValue();
						positionReadMin = se.getValue() - (se.getValue()%10);
						positionReadMax = positionReadMin +10;
						newPosition((int)positionReadMax);
						break;	

					case 1: // Bouton dans le premier port
						//Angle
						angleRead = 360 * se.getValue()/1000;
						newAngle(angleRead);
						break;

					case 2:// Cursor dans le second port
						//curseur= se.getValue();
						pressure = se.getValue();
						tapDetected(pressure);
						break;	

					}
				}
			});

			interfaceKitPhidget.addInputChangeListener(new InputChangeListener() {
				@Override
				public void inputChanged(InputChangeEvent arg0) {
				}
			});
		}catch(PhidgetException e) {
			e.printStackTrace();
		}

	}

	@Override
	public String toString()
	{
		return new String(this.name);
	}

	// Rotation detected
	public void newAngle(Double value){
		setChanged();
		notifyObservers(new Message(value));
	}

	// Vertical position changed
	public void newPosition(Integer position){
		setChanged();
		notifyObservers(new Message(position));
	}
	// Vertical position changed
	public void tapDetected(Double detected){
		setChanged();
		notifyObservers(new Message(true, detected));
	}
}
